<template>
  <div v-if="!isListVisible">
    <!-- 联络结果查询 -->
    <div style="height: 50px;">
      <div class="message">
        <el-radio></el-radio>联络结果查询
      </div>
      <!-- 当前展会 -->
      <div class="exhibition">当前展会:
        <el-text v-model="state.dataForm.exhsNameStr">{{ state.dataForm.exhsNameStr }} </el-text>
        <el-text class="mx-1" type="primary" style="padding-left: 16px;cursor: pointer;"
          @click="handlexhibition()">切换</el-text>
        <Sort
          style="width: 1em; height: 1em; margin-left: 10px;transform: rotate(270deg);color:#17B3A3;margin-bottom:-2px;margin-right: 12px;" />
      </div>
    </div>
    <el-form ref="vForm" :model="state.dataForm" @keyup.enter="state.getDataList()" label-width="85px">
      <el-form-item label="联络任务">
        <el-checkbox @change="handleCheckAllChange" v-model="allStufs">全选</el-checkbox>
      </el-form-item>
      <el-form-item v-if="isExhibitionSet" style="margin-left: -30px;">
        <el-checkbox-group class="select" v-model="state.tskIdArr" @change="getoperatorList">
          <el-checkbox v-for="item in taskleader" :key="item.id" :label="item.id" :value="item.id">
            {{ item.tskName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-row>
        <el-form-item label="操作人员">
          <el-select v-model="state.dataForm.sftId" placeholder="请选择" clearable>
            <el-option v-for="item in operatorList" :key="item.userId" :label="item.remark" :value="item.userId">
              {{ item.remark }}
            </el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="联络结果">
          <!--1未联络  2已联络 3失败 4待联络 5不联络-->
          <el-select v-model="state.dataForm.lrdLinkState" placeholder="请选择" @change="clearSecondarySelection">
            <el-option value="">请选择</el-option>
            <el-option v-for="item in state.linkResultArr" :key="item.id" :label="item.value" :value="item.id">
              {{ item.value }}
            </el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <!-- 未联络 -->
      <div v-if="state.dataForm.lrdLinkState == 1"></div>
      <!-- 已联络 -->
      <div v-if="state.dataForm.lrdLinkState == 2">
        <el-row>
          <el-form-item>
            <ren-checkbox-group v-model="state.dataForm.linkReason" dict-type="telephone_contacted"
              placeholder="请选择"></ren-checkbox-group>
          </el-form-item>
        </el-row>
      </div>
      <!-- 待联络 -->
      <div v-if="state.dataForm.lrdLinkState == 4">
        <el-row>
          <el-form-item>
            <ren-checkbox-group v-model="state.dataForm.linkReason" dict-type="wait_contact"
              placeholder="请选择"></ren-checkbox-group>
          </el-form-item>
        </el-row>
      </div>
      <!-- 不联络 -->
      <div v-if="state.dataForm.lrdLinkState == 5">
        <el-row>
          <el-form-item>
            <ren-checkbox-group v-model="state.dataForm.linkReason" dict-type="no_contact"
              placeholder="请选择"></ren-checkbox-group>
          </el-form-item>
        </el-row>
      </div>
      <!-- 失败 -->
      <div v-if="state.dataForm.lrdLinkState == 3">
        <el-row>
          <el-form-item>
            <ren-checkbox-group v-model="state.dataForm.linkReason" dict-type="telephone_fail"
              placeholder="请选择"></ren-checkbox-group>
          </el-form-item>
        </el-row>
      </div>
      <el-row>
        <el-form-item label="联络时间">
          <el-date-picker v-model="state.daterange" type="daterange" value-format="YYYY-MM-DD"
            :range-separator="$t('datePicker.range')" :start-placeholder="$t('datePicker.start')"
            :end-placeholder="$t('datePicker.end')"> </el-date-picker>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="联络时长">
          <el-input v-model="state.dataForm.linkMinTime" type="text" placeholder="请输入" style="width: 200px;"
            clearable></el-input>
        </el-form-item>
        <el-text style="font-size:16px;margin-top:-30px;padding: 10px 10px "> __</el-text>
        <el-form-item label-width="0px">
          <el-input v-model="state.dataForm.linkMaxTime" type="text" placeholder="请输入" style="width: 200px;"
            clearable></el-input>
        </el-form-item>
        <el-text style="margin-top:-20px;padding: 10px 10px ">秒</el-text>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item>
            <el-checkbox v-model="state.dataForm.dataBox" label="人员数据筐" name="type"></el-checkbox>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item>
            <el-button type="primary" @click="baseQuery()" :disabled="state.tskIdArr.length === 0">查询</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
  <!-- 当前展会弹窗 -->
  <exhibition ref="currentExhibition" @refreshDataList="getInfo" @refreshexhibitionlist="getresultleader"></exhibition>
  <!-- 查询列表  -->
  <div v-if="isListVisible" style="margin: 0;background:#fff" v-loading="state.dataForm.loading">
    <el-form label-position="left" label-width="14px" :inline="true" :model="state.dataForm"
      @keyup.enter="state.getDataList()">
      <div style="font-size: 16px; font-weight: 600; height: 50px;">
        <el-radio></el-radio>联络结果查询列表
      </div>
      <el-form-item>
        <el-button @click="redistribution()" v-if="isSingleTaskSelected">重新分配任务</el-button>
        <el-button type="primary" @click="toggleListVisibility()">返回</el-button>
      </el-form-item>
      <div v-if="isredistribution">
        <el-row>
          <el-col :span="24">
            <el-form-item>
              <el-checkbox @change="handleCheckAllChange2" v-model="state.dataForm.allStufs2">全选</el-checkbox>
            </el-form-item>
          </el-col>
          <el-form-item>
            <el-checkbox-group v-model="state.stufIdArr" style="margin-top:-20px;">
              <el-checkbox v-for="leader in operatorList" :key="leader.userId" :label="leader.userId"
                :value="leader.userId">{{ leader.remark }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item style="margin-top: 10px;">
            <el-button type="primary" v-model="state.dataForm.selectAll" @click="determine()"
              :disabled="!isStaffSelected" >全部分配</el-button>
            <el-button type="primary" @click="Selectallocation()" :disabled="!canSelectAllocation">选中分配</el-button>
          </el-form-item>
        </el-row>
      </div>
    </el-form>
    <el-table :header-cell-style="{ 'background': '#eef1f6', 'color': '#1f2d3d', 'border-color': '#dfe6ec' }"
      v-loading="state.dataListLoading" :data="state.dataList" border @selection-change="handleSelectionChange"
      style="width: 100%" :span-method="spanMethod">
      <el-table-column prop="id" type="selection"></el-table-column>
      <el-table-column align="center" prop="id" label="联络ID" width="70" show-overflow-tooltip></el-table-column>
      <el-table-column align="center" prop="lrdLinkState" label="联络状态" width="100" show-overflow-tooltip>
        <template v-slot="scope">
          <el-button v-if="scope.row.lrdLinkState == 1" type="success" plain style="width: 70px;">未联络</el-button>
          <el-button v-if="scope.row.lrdLinkState == 2" type="info" plain style="width: 70px;">已联络</el-button>
          <el-button v-if="scope.row.lrdLinkState == 3" type="info" plain style="width: 70px;">失败</el-button>
          <el-button v-if="scope.row.lrdLinkState == 4" type="info" plain style="width: 70px;">待联络</el-button>
          <el-button v-if="scope.row.lrdLinkState == 5" type="info" plain style="width: 70px;">不联络</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="lrdReason" label="联络结果" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column align="center" prop="personName" label="姓名" width="110" show-overflow-tooltip></el-table-column>
      <el-table-column align="center" prop="company" label="公司名称" width="200" show-overflow-tooltip></el-table-column>
      <el-table-column align="center" prop="mobile" label="联络号码" width="150" show-overflow-tooltip></el-table-column>
      <el-table-column align="center" prop="thyRecordFile" label="通话录音" width="220" show-overflow-tooltip>
        <template v-slot="scope">
          <div v-if="scope.row.thyRecordFile == null || scope.row.thyRecordFile == ''"></div>
          <audio v-else :src="scope.row.thyRecordFile" type="audio/mpeg" controls class="video"></audio>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="thyTimeSpan" label="通话时长" width="90"
        show-overflow-tooltip></el-table-column>
      <el-table-column align="center" prop="lrdRemark" label="联络备注" width="170" show-overflow-tooltip></el-table-column>
      <el-table-column align="center" prop="lrdUpdateTime" label="联络时间" width="160"
        show-overflow-tooltip></el-table-column>
      <el-table-column align="center" prop="lrdOwnerName" label="联络人" width="130"
        show-overflow-tooltip></el-table-column>
      <el-table-column :label="$t('handle')" fixed="right" header-align="center" align="center" width="70">
        <template v-slot="scope">
          <el-button v-if="state.hasPermission('crm:crmlinkrecord:delete')" link type="danger"
            @click="state.deleteHandle(scope.row.id)">{{ $t("delete") }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination :current-page="state.page" :page-sizes="[10, 20, 50, 100]" :page-size="state.limit"
      :total="state.total" layout="total, sizes, prev, pager, next, jumper" @size-change="state.pageSizeChangeHandle"
      @current-change="state.pageCurrentChangeHandle"> </el-pagination>
  </div>
</template>

<script lang="ts" setup>
import useView from "@/hooks/useView";
import { computed, nextTick, reactive, ref, toRefs, watch } from "vue";
import { ElMessage } from "element-plus";
import baseService from "@/service/baseService";
import exhibition from "./current-exhibition-add.vue";
import Template from "@/views/devtools/template.vue";
const view = reactive({
  getDataListURL: '/crm/crmlinkrecord/page',
  createdIsNeed: false,
  getDataListIsPage: true,
  deleteURL: '/crm/crmlinkrecord',
  deleteIsBatch: true,
  daterange: null,
  dataForm: {
    loading: false,
    loading2: false,
    linkBTime: null as number | null,//开始时间
    linkETime: null as number | null,//结束时间
    id: "",
    sftId: "",
    lrdLinkState: null as any,//联络状态
    linkResult: "",//联络结果
    linkReason: [] as any,//联络原因
    linkMinTime: "",//联络时长
    linkMaxTime: "",//联络时长大
    tskIdList: "",
    stufIdListStr: "",
    lrdIdListStr: "",
    // tskStufsList: [] as string[],
    dataBox: "",
    selectAll: false as any,
    exhsNameStr: "",
    curExhId: "",
    allStufs2:false as any,
  },
  linkResultArr: [
    { id: 1, value: "未联络" },
    { id: 2, value: "已联络" },
    { id: 3, value: "失败" },
    { id: 4, value: "待联络" },
    { id: 5, value: "不联络" },
  ],
  tskIdArr: [] as any[],
  stufIdArr: [] as any[],
});

//只选择一个任务 重新分配才能显示
const isSingleTaskSelected = computed(() => state.tskIdArr.length === 1 && state.dataForm.lrdLinkState === 1);

const isListVisible = ref(false);
//重新分配隐藏
const isredistribution = ref(false);



//初始化
const init = () => {
  getresultleader();
  getoperatorList()
  getInfo()
};
/**
 * 获取当前登录用户信息，当前展会
 */
const getInfo = () => {
  return baseService.get("/sys/user/info").then((res) => {
    if (res.data.exhsNameStr == "" || res.data.exhsNameStr == "null" || res.data.exhsNameStr == null) {
      alert("请先设置当前展会");
      isExhibitionSet.value = false;
    } else {
      Object.assign(state.dataForm, res.data);
      isExhibitionSet.value = true;
    }
  });
};

const currentExhibition = ref();
const handlexhibition = (id?: number) => {
  nextTick(() => {
    currentExhibition.value.init(id);
  });
};

const isExhibitionSet = ref(true);

//清除2级标签
const clearSecondarySelection = () => {
  state.dataForm.linkReason = "";
};

//返回上一页
const toggleListVisibility = () => {
  isListVisible.value = !isListVisible.value;
  isredistribution.value = false;
  state.dataForm.lrdLinkState = "";
  state.dataForm.linkReason = '';
  state.tskIdArr = [];
  state.stufIdArr=[];
  state.daterange = null;
  state.dataForm.sftId = "";
  state.dataForm.linkMinTime = "";
  state.dataForm.linkMaxTime = "";
  operatorList.value = [];
  state.dataForm.dataBox = "";
};


/**
 * 查询按钮
 */
const baseQuery = () => {
  //清理上一次查询的数据
  state.dataList = [];
  state.page = 1;
  state.total = 0;
  isListVisible.value = !isListVisible.value;
  // 联络任务获取id
  state.dataForm.tskIdList = state.tskIdArr ? state.tskIdArr.join(",") : '';
  state.dataForm.linkReason = state.dataForm.linkReason ? state.dataForm.linkReason.join(",") : '';
  // 重新获取数据列表
  state.getDataList();
};


//获取当前表格人员id
const handleSelectionChange = (val: any) => {
  state.dataForm.lrdIdListStr = val.map((item: { id: any; }) => item.id).join(',');

}

//计算属性，判断是否可以点击选中全配按钮
const isStaffSelected = computed(() => {
  return state.stufIdArr.length > 0
});

//计算属性，判断是否可以点击选中分配按钮
const canSelectAllocation = computed(() => {
  return isStaffSelected.value && state.dataForm.lrdIdListStr !== '';
})


/**
 * 全选分配按钮
 */
const determine = () => {
  state.dataForm.loading = true;
  state.dataForm.stufIdListStr = state.stufIdArr ? state.stufIdArr.join(",") : '';
  baseService.put("/crm/crmlinkrecord/reallocate", {
    selectAll: true,
    stufIdListStr: state.dataForm.stufIdListStr,
    lrdIdListStr: state.dataForm.lrdIdListStr,
    paramsMap: state.dataForm,
    total: state.total
  }).then((res) => {
    if (res.code == 0) {
      isredistribution.value = false;
      state.stufIdArr = [];
      // 重新获取数据列表
      state.getDataList();
      state.dataForm.loading = false
      state.dataForm.allStufs2 = false
      return ElMessage.success("分配成功");
    }
  });
}



/**
 * 选中分配按钮
 */
const Selectallocation = () => {
  //工作人员获取id
  state.dataForm.loading = true;
  state.dataForm.stufIdListStr = state.stufIdArr ? state.stufIdArr.join(",") : '';
  baseService.put("/crm/crmlinkrecord/reallocate", {
    selectAll: false,
    stufIdListStr: state.dataForm.stufIdListStr,
    lrdIdListStr: state.dataForm.lrdIdListStr,
    paramsMap: state.dataForm
  }).then((res) => {
    if (res.code == 0) {
      isredistribution.value = false;
      state.stufIdArr = [];
      // 重新获取数据列表
      state.getDataList();
      state.dataForm.loading = false
      state.dataForm.allStufs2 = false
      return ElMessage.success("分配成功");
    }
  });
}

/**
* 重新分配显示隐藏
*/
const redistribution = () => {
  isredistribution.value = !isredistribution.value;
}


/**
 * 操作人员-全选
 * @param val
 */
const handleCheckAllChange2 = (val: boolean) => {
  // 选中
  if (val) {
    for (let i = 0; i < operatorList.value.length; i++) {
      state.stufIdArr.push(operatorList.value[i].userId);
    }
  } else {
    state.stufIdArr = [];
  }
}


const taskleader = ref([] as any[]);
/**
 * 联络结果-全选
 * @param val
 */
const handleCheckAllChange = (val: boolean) => {
  // 选中
  if (val) {
    for (let i = 0; i < taskleader.value.length; i++) {
      state.tskIdArr.push(taskleader.value[i].id);
    }
  } else {
    state.tskIdArr = [];
  }
}

/**
 * 获取联络结果
 */
const getresultleader = () => {
  return baseService.get("/crm/crmtask/pageByUserId", { page: 1, limit: 100, isNeedExhId: 1 }).then((res) => {
    if (res.code !== 0) {
      return ElMessage.error(res.msg);
    }
    taskleader.value = res.data.list;
    console.log(taskleader.value)
  });
};

/**
 *操作人员列表
 */
const operatorList = ref<any[]>([]);
const getoperatorList = () => {
  return baseService.post("/sys/user/queryUserList", { ids: state.tskIdArr ? state.tskIdArr.join(",") : '' }).then((res) => {
    operatorList.value = res.data;
  });
};


const state = reactive({ ...useView(view), ...toRefs(view) });

watch(
  () => state.daterange,
  (val: number[] | null) => {
    if (val === null) {
      state.dataForm.linkBTime = null;
      state.dataForm.linkETime = null;
    } else {
      state.dataForm.linkBTime = val[0];
      state.dataForm.linkETime = val[1];
    }
  }
);

const allStufs = ref(false); // 全选
// 监听state.dataForm.tskStufsList的变化
watch(() => state.tskIdArr, (newStufsList, oldStufsList) => {
  allStufs.value = newStufsList.length === taskleader.value.length;
});

const allStufs2 = ref(false); // 全选
// 监听state.dataForm.tskStufsList的变化
watch(() => state.stufIdArr, (newStufsList, oldStufsList) => {
  allStufs2.value = newStufsList.length === operatorList.value.length;
});

// // 需要合并的列
// const needToMergeColumns = ['id','lrdLinkState','lrdReason','personName','company','lrdRemark','lrdOwnerName'];
const needToMergeColumns = ['id'];
/**
 * 合并单元格
 * @param row
 * @param column
 * @param rowIndex
 * @param columnIndex
 */
const spanMethod = ({ row, column, rowIndex, columnIndex }: {
  row: any;
  column: any; // 这里类型可以更准确，但通常由 Element Plus 内部定义
  rowIndex: number;
  columnIndex: number;
}) => {
  console.log(row);
  console.log(column);
  console.log(rowIndex, columnIndex);
  if (needToMergeColumns.indexOf(column.property) !== -1) {
    // 获取当前单元格的值
    const currentValue = row[column.property];
    // 获取上一行相同列的值
    const preRow = state.dataList ? state.dataList[rowIndex - 1] : null;
    const preValue = preRow ? preRow[column.property] : null;
    // 如果当前值和上一行的值相同，则将当前单元格隐藏
    if (currentValue === preValue) {
      return { 'rowspan': 0, 'colspan': 0 };
    } else {
      // 否则计算当前单元格应该跨越多少行
      let rowspan = 1;
      if (state.dataList) {
        for (let i = rowIndex + 1; i < state.dataList.length; i++) {
          const nextRow = state.dataList[i];
          const nextValue = nextRow[column.property];
          if (nextValue === currentValue) {
            rowspan++;
          } else {
            break;
          }
        }
      }
      return { 'rowspan': rowspan, 'colspan': 1 };
    }
  }
};

//页面进入执行
init();

</script>

<style lang="scss" scoped>
.select {
  width: 800px;
  margin-top: -15px;
  margin-left: 30px;
}

.message {
  float: left;
  font-size: 16px;
  font-weight: 600;
}

.exhibition {
  float: right;
  font-size: 14px;
  padding-left: 20px;
  height: 35px;
  line-height: 35px;
  border-radius: 27px;
  background-color: rgba(247, 247, 247, 1);
}

::v-deep .video {
  width: 170px;
  height: 25px;
}

.el-checkbox {
  width: 150px;
}
</style>
